package com.terry.proxy.application.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.terry.proxy.application.cache.DBServerCache;
import com.terry.proxy.application.cache.DBServerCacheImpl;
import com.terry.proxy.application.dao.ProxyClientDao;
import com.terry.proxy.application.dto.ProxyClientInsertDTO;
import com.terry.proxy.application.entity.ProxyClient;
import com.terry.proxy.application.entity.ProxyClientTunnel;
import com.terry.proxy.application.service.ProxyClientService;
import com.terry.proxy.application.service.ProxyClientTunnelService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 客户端(ProxyClient)表服务实现类
 *
 * @author terry
 * @since 2022-12-08 20:54:22
 */
@Service("proxyClientService")
public class ProxyClientServiceImpl extends ServiceImpl<ProxyClientDao, ProxyClient> implements ProxyClientService {

    @Resource
    private ProxyClientDao proxyClientDao;

    @Resource
    private ProxyClientTunnelService proxyClientTunnelService;

    @Transactional
    public synchronized boolean insertUnion(ProxyClientInsertDTO proxyClientInsertDTO){
        ProxyClient proxyClient = proxyClientInsertDTO.getProxyClient();
        ProxyClientTunnel proxyClientTunnel = proxyClientInsertDTO.getProxyClientTunnel();
        // 新增客户端
        boolean isSuccess = proxyClientDao.insert(proxyClient) > 0;
        if (proxyClientTunnel != null) {
            proxyClientTunnel.setClientId(proxyClient.getId());
            // 获取最大的端口
            int maxPort = proxyClientTunnelService.getMaxPort();
            proxyClientTunnel.setServerPort(maxPort);
            // 新增隧道
            isSuccess = proxyClientTunnelService.save(proxyClientTunnel);
            // 添加绑定
            DBServerCacheImpl dbServerCache = SpringUtil.getBean(DBServerCacheImpl.class);
            dbServerCache.addClient(proxyClient, Arrays.asList(proxyClientTunnel));
        }
        return isSuccess;
    }
}

